package name.williamwall.buxoid;
/**
 * This software is made available under the Gnu General Public License v3
 * and has absolutely no waranty. You may change the software to suit your needs.
 * 
 * Author: William Wall, IV
 */
import android.app.DatePickerDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class BudgetList extends ListActivity {	
	// menu ids
	private static final int ADD_ID = Menu.FIRST;
	private static final int EDIT_ID = Menu.FIRST + 1;
	private static final int DELETE_ID = Menu.FIRST + 2;
	private static final int UPDATE_ID = Menu.FIRST + 3;
	private static final int SETTINGS_ID = Menu.FIRST + 4;
	private static final int HELP_ID = Menu.FIRST + 5;
	
	private Button mMonthButton;
	private long mContextSelectedId;
	private static final String [] MONTHS = new String [] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
	
	@Override
	protected void onCreate(Bundle state) {
		super.onCreate(state);
	    
	    setContentView(R.layout.list_budgets);
		
        Button prev = (Button) findViewById(R.id.list_budgets_prev);
        mMonthButton = (Button) findViewById(R.id.list_budgets_month);
        Button next = (Button) findViewById(R.id.list_budgets_next);
        
        prev.setOnClickListener(new View.OnClickListener () {
			public void onClick(View view) {
				Buxoid.prevMonth();
				fillData();
			}
		});
		
		next.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Buxoid.nextMonth();
				fillData();
			}
		});
		
		mMonthButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				new DatePickerDialog(BudgetList.this, mDateSetListener, Buxoid.mYear, Buxoid.mMonth, 1).show();
			}
		});
		
		registerForContextMenu(getListView());
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		fillData();
	}

	private void fillData() {
	    try {
    //		Log.d("Buxfer", "filling budget data");
    		setTitle("Buxoid: Budgets");
    		int month = Buxoid.mMonth;
    		int year = Buxoid.mYear;
    		
    		mMonthButton.setText(MONTHS[month] + " " + year);
    		
    		// get all of the budgets
    		Cursor c = Buxoid.mDb.fetchAllBudgets(month+1, year);
    		startManagingCursor(c);
    		
    		String [] from = new String [] {
    				BuxoidDb.TAG_NAME,
    				BuxoidDb.TAG_LIMIT,
    				BuxoidDb.TAG_LIMIT
    		};
    		
    		int [] to = new int [] {
    				R.id.row_budget_tag,
    				R.id.row_budget_amount,
    				R.id.row_budget_bar
    		};
    		
    		BudgetAdapter bAdapter = new BudgetAdapter(this, R.layout.row_budget, c, from, to, month + 1, year, Buxoid.mDb);
    		setListAdapter(bAdapter);
	    } catch (IllegalStateException e) {
            // this happens when the user starts an update and navigates away from the app
            // so just ignore it
        }
	}
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuItem item;
		
		item = menu.add(0, ADD_ID, 1, R.string.menu_add);
		item.setIcon(android.R.drawable.ic_menu_add);
		
		// set update menu item and icon
        item = menu.add(1, UPDATE_ID, 2, R.string.menu_update);
        item.setIcon(android.R.drawable.ic_menu_set_as);
        
        // set settings menu item and icon
        item = menu.add(1, SETTINGS_ID, 3, R.string.menu_settings);
        item.setIcon(android.R.drawable.ic_menu_preferences);
        
        // set help menu item and icon
        item = menu.add(1, HELP_ID, 4, R.string.menu_help);
        item.setIcon(android.R.drawable.ic_menu_help);
        
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Intent i;
		int id = item.getItemId();
		switch (id) {
		case ADD_ID:
			i = new Intent(this.getParent(), EditBudget.class);
			startActivity(i);
			return true;
		case UPDATE_ID:
		    Buxoid.mUICallback = new Handler();
            Buxoid.mFinish = new Runnable () {
                public void run () {
                    fillData();
                }
            };
        	Buxoid.update(this);
        	return true;
        case SETTINGS_ID:
        	i = new Intent(this, EditSettings.class);
            startActivity(i);
            return true;
		case HELP_ID:
			i = new Intent(this, Help.class);
			i.putExtra("topic", "Budgets");
			this.startActivity(i);
			return true;
		}
		
		return super.onMenuItemSelected(featureId, item);
	}

	/**
	 * This method creates the context menu on a long click
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		// set context selected id
		AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo; 
		mContextSelectedId = acmi.id;
//		Log.d("Buxfer", "context menu " + mContextSelectedId);
		
		// set up context menu header
		menu.setHeaderIcon(R.drawable.context_menu);
		TextView tv = (TextView) acmi.targetView.findViewById(R.id.row_budget_tag);
		menu.setHeaderTitle(tv.getText());
		
		// set up context menu options
		MenuItem item;
		item = menu.add(0, EDIT_ID, 1, R.string.menu_edit);
		item.setIcon(android.R.drawable.ic_menu_edit);
		
		item = menu.add(0, DELETE_ID, 2, R.string.menu_delete);
		item.setIcon(android.R.drawable.ic_menu_delete);
		
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	/**
	 * Handles the selection from the context menu (long click menu).
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case EDIT_ID:
			Intent i = new Intent(this, EditBudget.class);
			i.putExtra(EditBudget.BUDGET_ID, mContextSelectedId);
			startActivity(i);
			return true;
		case DELETE_ID:
			Buxoid.mDb.deleteBudget(mContextSelectedId);
			fillData();
			return true;
		}
		return super.onContextItemSelected(item);
	}

	/**
	 * When a budget is clicked on, pop up a window to edit it.
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
//		Log.d("Buxfer", "list item " + id + " clicked");
		Cursor c = Buxoid.mDb.fetchTag(id);
		if (c.getCount() > 0 && c.moveToFirst()) {
		    Buxoid.mViewTag = c.getString(c.getColumnIndex(BuxoidDb.TAG_NAME));
		}

        Buxoid parent = (Buxoid) this.getParent();
        parent.getTabHost().setCurrentTabByTag("transactions");
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int month, int day) {
        	Buxoid.mYear = Math.min(year, Buxoid.mYear);
        	Buxoid.mMonth = Math.min(month, Buxoid.mMonth);
        	fillData();
        }
    };
}
